package com.ddx.service.impl;

import com.ddx.common.enums.ErrorCode;
import com.ddx.common.enums.OrderStatus;
import com.ddx.common.enums.PayType;
import com.ddx.common.enums.ResultType;
import com.ddx.common.exception.BusinessException;
import com.ddx.common.util.DateUtil;
import com.ddx.common.util.JsonUtils;
import com.ddx.dao.*;
import com.ddx.pay.WeChatPayDto;
import com.ddx.pay.WeChatRequestPayDto;
import com.ddx.pay.WeixinPay;
import com.ddx.pojo.*;
import com.ddx.service.IAccountService;
import com.ddx.service.IShoppingOrderService;
import com.ddx.service.IShoppingPayService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author dudianbo
 * @ClassName: ${CLASSNAME}
 * @Description: ${DESCRIPTION}
 * @date 2018/9/6
 */
@Service
public class ShoppingPayServiceImpl implements IShoppingPayService {
    private static Logger logger = LoggerFactory.getLogger(ShoppingPayServiceImpl.class);
    @Autowired
    IAccountService iAccountService;
    @Autowired
    ShoppingOrderMapper shoppingOrderMapper;
    @Autowired
    IShoppingOrderService iShoppingOrderService;
    @Autowired
    ShoppingOrderDetailMapper shoppingOrderDetailMapper;
    @Autowired
    ShoppingSpecMapper shoppingSpecMapper;
    @Autowired
    ShoppingPayFlowMapper shoppingPayFlowMapper;
    @Autowired
    ShoppingProductMapper shoppingProductMapper;
    @Autowired
    WeixinPay weixinPay;
    /**
     * 余额支付
     * @param orderId
     */
    @Override
    @Transactional
    public void balancePay(String orderId) {
        logger.info("余额支付接口入参orderId={}",orderId);
        ShoppingOrder shoppingOrder=shoppingOrderMapper.selectOrderByOrderId(orderId);
        if(!shoppingOrder.getStatus().equals(OrderStatus.DAIFUKUAN.getValue())){
            logger.error("订单状态非待付款，不能进行支付orderId={}",orderId);
            throw new BusinessException(ErrorCode.BUSSINESS_ERROR_210);
        }
        List<ShoppingOrderDetail>  orderDetails=shoppingOrderDetailMapper.selectOrderDetailByOrderId(orderId);
        for(ShoppingOrderDetail shoppingOrderDetail:orderDetails){
            ShoppingSpec shoppingSpec=shoppingSpecMapper.selectByPrimaryKeyForUpdate(Integer.parseInt(shoppingOrderDetail.getSpecId()));
            if(Integer.parseInt(shoppingSpec.getSpecStock())<shoppingOrderDetail.getNumber()){
                logger.error("产品已售罄orderId={}",orderId);
                //产品已售罄 修改订单状态
                ShoppingOrder record=new ShoppingOrder();
                record.setStatus(OrderStatus.YISHOUQING.getValue());
                record.setOrderId(orderId);
                shoppingOrderMapper.updateByOrderId(record);
                throw new BusinessException(ErrorCode.BUSSINESS_ERROR_211);
            }
            ShoppingSpec record=new ShoppingSpec();
            record.setId(Integer.parseInt(shoppingOrderDetail.getSpecId()));
            Integer stock=Integer.parseInt(shoppingSpec.getSpecStock())-shoppingOrderDetail.getNumber();
            record.setSpecStock(stock.toString());
            shoppingSpecMapper.updateByPrimaryKeySelective(record);
        }
        Transaction transaction=new Transaction();
        transaction.setAmount(shoppingOrder.getPtotal());
        transaction.setUserId(shoppingOrder.getUserId());
        transaction.setOrderId(orderId);
        transaction.setAccountType(1);
        transaction.setRemark("购买产品");
        iAccountService.reduce(transaction);
        //支付成功页面
        ShoppingPayFlowWithBLOBs shoppingPayFlow=new ShoppingPayFlowWithBLOBs();
        shoppingPayFlow.setOrderId(orderId);
        shoppingPayFlow.setPayType(PayType.BALANCE_PAY.getValue());
        shoppingPayFlow.setAmount(shoppingOrder.getPtotal());
        shoppingPayFlow.setDealStatus(ResultType.SUCCESS.getCode());
        shoppingPayFlow.setTimeEnd(DateUtil.format(new Date(),DateUtil.YYYYMMDD_HHMMSS));
        shoppingPayFlow.setUserId(shoppingOrder.getUserId());
        iShoppingOrderService.paySuccess(shoppingPayFlow);
    }

    @Override
    public void createPayFlow(ShoppingPayFlowWithBLOBs record) {
        shoppingPayFlowMapper.insertSelective(record);
    }
    /**
     * 微信支付
     * @param orderId
     */
    @Override
    public WeChatPayDto WeChatPay(String orderId, String ip) {
        ShoppingOrder shoppingOrder=shoppingOrderMapper.selectOrderByOrderId(orderId);
        if(shoppingOrder==null){
            throw new BusinessException(ErrorCode.BUSSINESS_ERROR_206);
        }
        WeChatRequestPayDto weChatRequestPayDto=new WeChatRequestPayDto();
        weChatRequestPayDto.setTotal_fee((shoppingOrder.getPtotal().movePointRight(2)).toString());
        weChatRequestPayDto.setOut_trade_no(orderId);
        weChatRequestPayDto.setBody(shoppingOrder.getRemark());
        weChatRequestPayDto.setTrade_type("MWEB");
        weChatRequestPayDto.setSpbill_create_ip(ip);
        weChatRequestPayDto.setBody("短视频");
        logger.info("获取客户端ip={}",ip);
        WeChatPayDto weChatPayDto=weixinPay.payUnifiedorder(weChatRequestPayDto);
        ShoppingPayFlow shoppingPayFlow=new ShoppingPayFlow();
        shoppingPayFlow.setOrderId(orderId);
        List<ShoppingPayFlowWithBLOBs> list=shoppingPayFlowMapper.selectByRecord(shoppingPayFlow);
        if(list==null||list.size()==0){
            ShoppingPayFlowWithBLOBs record=new ShoppingPayFlowWithBLOBs();
            record.setOrderId(orderId);
            record.setAmount(shoppingOrder.getPtotal());
            record.setDealStatus(ResultType.PROCESSING.getCode());
            record.setPayType(PayType.WECHAT_PAY.getValue());
            record.setUserId(shoppingOrder.getUserId());
            record.setBeforeSendRecord(JsonUtils.objToJson(weChatRequestPayDto));
            shoppingPayFlowMapper.insertSelective(record);
        }
        return weChatPayDto;
    }


}
